package servlets.category;

import hibernate.method.CategoryMethods;
import hibernate.method.GameCategoryMethods;
import hibernate.model.Category;
import hibernate.model.GameCategory;
import hibernate.util.HibernateUtil;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 * Servlet implementation class CategoryDelete
 */
@WebServlet("/CategoryDelete")
public class CategoryDelete extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CategoryDelete() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
		
		String category = request.getParameter("check");
		int category_id = Integer.parseInt(category);
		
		SessionFactory sessionFactory = HibernateUtil
				.getSessionAnnotationFactory();
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		CategoryMethods catm = new CategoryMethods();
		GameCategoryMethods gcatm = new GameCategoryMethods();
		Category cat = catm.idToCategory(sessionFactory, session, category_id);
		catm.deleteCategory(sessionFactory, session, cat);
		List<GameCategory> gcat = new ArrayList<GameCategory>(gcatm.listByCategory(sessionFactory, session, category_id));
		for (GameCategory gcat1 : gcat){
			session.delete(gcat1);
		}
		
		
		
		
		try {
			session.getTransaction().commit();
			out.println("<script type=\"text/javascript\">alert(\"Kategoria zostala usunieta\"); window.location.href = \"management/index.jsp?page=games&group=categoryManagement\";</script>");

		} catch (Exception e) {
			out.println("<script type=\"text/javascript\">alert(\"Kategoria nie zostala usunieta\"); window.location.href = \"management/index.jsp?page=games&group=categoryManagement\";</script>");

		}
		
		
		
	}

}
